(function(global){

  function Quad(gl, x, y, level, screen){
    const self = this;

    self.gl = gl;
    self.x = x;
    self.y = y;
    self.level = level;
    self.url = "http://mt2.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}";
    let realUrl = self.url;

    realUrl = realUrl.replace('{x}', x);
    realUrl = realUrl.replace('{y}', y);
    realUrl = realUrl.replace('{z}', level);

    self.realUrl = realUrl;

    // 0 正在请求图片中 1 请求完成 2 请求失败 需要重新请求
    self.status = 0;
    // 网格
    const boundary = tileXYToRadians(self.x, self.y, self.level);

    const posTopLeft = [boundary.west, boundary.north];
    const posTopRight = [boundary.east, boundary.north];
    const posBottomLeft = [boundary.west, boundary.south];
    const posBottomRight = [boundary.east, boundary.south];

    const worldTopLeft = tileLonlatRadians2world(posTopLeft);
    const worldTopRight = tileLonlatRadians2world(posTopRight);
    const worldBottomLeft = tileLonlatRadians2world(posBottomLeft);
    const worldBottomRight = tileLonlatRadians2world(posBottomRight);

    // gl相关
    self.quadBufferVertices = initBuffer(gl, gl.ARRAY_BUFFER,
      new Float32Array([
        worldTopLeft[0], 0.0, worldTopLeft[1],
        worldTopRight[0], 0.0, worldTopRight[1],
        worldBottomLeft[0], 0.0, worldBottomLeft[1],
        worldBottomRight[0], 0.0, worldBottomRight[1]
      ]));
    self.quadBufferUV = initBuffer(gl, gl.ARRAY_BUFFER,
      new Float32Array([
        0.0, 0.0,
        1.0, 0.0,
        0.0, 1.0,
        1.0, 1.0
      ]));
    self.quadBufferIndices = initBuffer(gl, gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 1, 3, 2]));
    self.texture = gl.createTexture();
    self.textureInit = false;

    // 图片
    self.image = new Image();
    self.image.crossOrigin = '';
    self.image.onload = () => {
      self.status = 1;
    };
    self.image.onerror = () => {
      console.warn(`there is an error in image of ${self.realUrl}`);
      self.status = 2;
    };
    self.image.src = self.realUrl;
  }

  global.Quad = Quad;

})(window);
